//
//  NavigationController.swift
//  HeadlineNews
//
//  Created by han on 2019/5/30.
//  Copyright © 2019 han. All rights reserved.
//

import UIKit

class NavigationController: UINavigationController {
    var navigationDelegate: NavigationDelegate?
    
    // 是否是自定义手势返回(只能配合自定义转场使用)，或者系统手势
    var isCustomPopGesture: Bool = false
    
    private var isPopGestureEnable: Bool?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 用于自定义push转场动画
        self.navigationDelegate = NavigationDelegate(navigationController: self)
        self.delegate = self.navigationDelegate
        self.isCustomPopGestureEnable(false)
    }
    
    // 设置自定义手势或者系统手势
    func isCustomPopGestureEnable(_ isEnabled: Bool) {
        self.isCustomPopGesture = isEnabled
        self.navigationDelegate?.isPopGestureEnabled(isEnabled: isEnabled)
    }
    
    // 设置是否允许测滑
    func isInteractivePopGestureEnable(_ isEnabled: Bool) {
        if isPopGestureEnable == isEnabled { return }
    
        isPopGestureEnable = isEnabled
        self.interactivePopGestureRecognizer?.isEnabled = isEnabled
        if isEnabled {
             self.interactivePopGestureRecognizer?.delegate = self
        } else {
             self.interactivePopGestureRecognizer?.delegate = nil
        }
    }
    
}

// 当采用系统返回手势时，要注意当counts只有一个时，容易引起界面卡死.
// 解决这个方法，不能单纯判断是否在首页。需要将代理关闭，并关闭手势
extension UINavigationController: UIGestureRecognizerDelegate {
    public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer == navigationController?.interactivePopGestureRecognizer {
            if viewControllers.count < 2 || visibleViewController == viewControllers.first {
                return  false
            }
        }
        return true
    }
    
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) && otherGestureRecognizer.isKind(of: UIScreenEdgePanGestureRecognizer.self) {
            return true
        }
        return false
    }
}

extension NavigationController {
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if viewControllers.count > 0 {
            viewController.hidesBottomBarWhenPushed = true
        }
        super.pushViewController(viewController, animated: animated)
    }
    
}


// MARK: 隐藏navigationBar & 系统手势测滑

var hideNavigationBarKey = 102
var popGestureKey = 103

extension UIViewController {
    // 设置当前VC是否隐藏navigationBar
    var hideNavigationBarIfNeeded: Bool {
        set {
            objc_setAssociatedObject(self, &hideNavigationBarKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
        }
        get {
            if let rs = objc_getAssociatedObject(self, &hideNavigationBarKey) as? Bool {
                return rs
            }
            return false
        }
    }
    
    // 设置当前VC是否允许手势返回
    var popGestureEnable: Bool {
        set {
            objc_setAssociatedObject(self, &popGestureKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
        }
        get {
            if let rs = objc_getAssociatedObject(self, &popGestureKey) as? Bool {
                return rs
            }
            return true
        }
    }
    
}

extension NavigationDelegate {
    /**
     生命周期：
     push 时：viewDidLoad -> viewWillAppear -> willShow -> viewDidAppear -> didShow
     pop 成功时：viewWillDisappear （此时已经pop出栈了）-> willShow -> viewDidDisappear -> didShow -> deinit
     pop 失败时：当前页：viewWillDisappear -> willShow -> viewWillAppear -> viewDidAppear 而上一页执行：viewWillAppear -> willShow -> viewWillDisappear -> viewDidDisappear
     
    */
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        // push & pop 这个方法在viewWillAppear之后调用
        print("willShow", navigationController.children, viewController)
        // 设置隐藏
        navigationController.setNavigationBarHidden(viewController.hideNavigationBarIfNeeded , animated: true)
        
    }
    
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        print("didShow", navigationController.children, viewController)
        // 设置是否允许测滑： 解决首页测滑卡死
        if let navigationC = navigationController as? NavigationController {
            if navigationC.isCustomPopGesture { return } // 自定义手势
            
            if navigationController.viewControllers.count <= 1 { // 系统手势处理，首页不允许返回
                navigationC.isInteractivePopGestureEnable(false)
            } else { // 判断当前VC是否允许测滑返回
                navigationC.isInteractivePopGestureEnable(viewController.popGestureEnable)
            }
        }
    }
}

/*
 测滑返回到指定界面：在需要指定界面中重新设置入栈队列
 override func viewDidAppear(_ animated: Bool) {
 super.viewDidAppear(animated)
 updateStack()
 }
 
 func updateStack() {
 guard let children = self.navigationController?.viewControllers, case var childrenVCs as [UIViewController] = NSMutableArray(array: children)  else { return }
 
 let count = childrenVCs.count
 
 guard  count > 2 else { return }
 // 判断上一个入栈的是否是NewsDetailViewController类型
 guard let _: NewsListViewController = childrenVCs[count - 2] as? NewsListViewController  else { return  }
 childrenVCs.remove(at: count - 2)
 //        // 删除上一条入栈
 //        last.willMove(toParent: nil)
 //        last.view.removeFromSuperview()
 //        last.removeFromParent()
 // 这样做会导致导航栏被移除的VC前一个VC继承。
 self.navigationController?.viewControllers = childrenVCs
 }
 */




